<?php
/**
 * 用户信息
 */
namespace app\api\controller;
use app\api\model\AccountAddress as AccountAddressModel;
use app\api\model\BaseConfig as BaseConfigModel;
use app\api\model\MemberLevel as MemberLevelModel;
use app\common\common;
use app\api\model\Member as MemberModel;
use app\admin\model\Member as AdminMembeModel;
use app\common\model\MemberCurrency as MemberCurrencyModel;
use app\common\model\MemberMatrix as MemberMatrixModel;
use app\api\model\MemberDonation as MemberDonationModel;
use app\api\model\MemberMining as MemberMiningModel;
use app\api\model\MemberArithmeticalPower as MemberArithmeticalPowerModel;
use app\common\model\UserMoneyLog;
use think\cache\driver\Redis;

class Member extends Baek
{
    /**
     * 用户余额
     * @return \think\Response
     */
    function wallet(){
        $wallet = MemberModel::wallet($this->mid);

        //获取用户详情
        $member = MemberModel::getDetails($this->mid);
        //读取用户等级详情
        $level = MemberLevelModel::getDetails($member['level_id']);
        //等级名称
        $wallet['level_name']   = $level['name'];
        $wallet['level']   = $level['level'];

        api_success($wallet);
    }

    /**
     * 获取我的邀请码
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function invitation(){
        //邀请码方式
        $member_code = BaseConfigModel::config_data('member_code');
        $member = MemberModel::getDetails($this->mid);
        if($member_code == 1){
            $code = $member['invitation'];
        }else{
            $code = $member['username'];
        }
        return api_success($code);
    }
    
    
     function my_team_src(){
        $page = $this->request->post('page', 1, 'serach_in');
        $limit = $this->request->post('limit', 20, 'serach_in');
        //我的直推人列表
        $list = MemberModel::where(['pid'=>$this->mid])->field('id,username,level_id,direct,create_time')->order('id desc')->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();
        //查询我的信息
        $member = MemberModel::getDetails($this->mid);

        foreach ($list['data'] as &$v){
            $v['team_num'] = MemberModel::where('team_id','like','%,'.$v['id'].',%')->count();
            $level = MemberLevelModel::getDetails($v['level_id']);
            $v['level_name'] = !empty($level) ? $level['name'] : '游客';
            unset($v['id'],$v['level_id']);
        }

        $team_num = MemberModel::where('team_id','like','%,'.$this->mid.',%')->count();

        $data = [
            'list'  =>  $list,
            'direct'    =>  $member['direct'],
            'team_num'  =>  $team_num,
        ];
        api_success($data);
    }

   

    function my_team(){
        $page = $this->request->post('page', 1, 'serach_in');
        $limit = $this->request->post('limit', 20, 'serach_in');
        
        //$member = MembeModel::getDetails($id);
        $member = MemberModel::getDetails($this->mid);

        //查询用户等级
        $level_list = MemberLevelModel::getMemberList();
        $level = [];
        foreach ($level_list as $v){
            $level[$v['id']] = $v;
            if($v['level'] == 0) $level[0] = $v;
        }
        


        //查询整个矩阵图
        $list = AdminMembeModel::member_matrix($member['position'],$level);
        $ret=[];
        $total=0;
        if(!empty($list['children'])){
            foreach ($list['children'] as $c){
              $id=explode("|",$c['name'])[0];
              $id=trim($id);
              //api_success($p1);
              
              $v = MemberModel::getDetails($id);
              //$v['team_num'] = MemberModel::where('team_id','like','%,'.$id.',%')->count();
              $num=1;
              if(!empty($c['children'])){
                  $this->get_team_num($num,$c['children']);
              }
              $v['team_num']=$num;
              $total+=$num;
              
              $level = MemberLevelModel::getDetails($v['level_id']);
              $v['level_name'] = !empty($level) ? $level['name'] : '游客';
            
              unset($v['id'],$v['level_id']);
              array_push($ret,$v);
             }
        }
        
        
        //api_success($ret);
        
        //$team_num = MemberModel::where('team_id','like','%,'.$this->mid.',%')->count();
        //$team_num =$total;
        
        $info=[
            "total" => count($ret),
            "data" =>$ret
        ];
        
        $data = [
            'list'  =>  $info,
            'direct'    =>  $member['direct'],
            'team_num'  =>  $total,
        ];
        api_success($data);
    }
    
    
    
    function get_team_num(&$num,$children){
        if(empty($children)){
            return;
        }
        $num+=count($children);
        foreach($children as $c){
            if(empty($c['children'])){
                continue;
            }
            $this->get_team_num($num,$c['children']);
        }
    }

    /**
     * 签到
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException\
     */
    function sign(){
        $staus = MemberModel::up_sign($this->mid);
        if(!$staus) return api_error('','Signed in today',$this->language);
        return api_success();
    }

    /**
     * 用户充值地址
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function recharge_address(){
//        $trc = trc_address($this->mid)['data'];
//        $bep = bep_address($this->mid)['data'];
//        return api_success(['trc' => $trc,  'bep' => $bep]);
        $trc = BaseConfigModel::config_data('usdt_address');
        $bep = BaseConfigModel::config_data('bep_usdt_address');
        return api_success(['trc' => $trc,  'bep' => $bep]);
    }

    /**
     * 我的社区算力矿机
     * @return \think\Response
     */
    function me_mining_info(){
        $redis = new Redis(config('cache.stores.redis'));
        $team = MemberModel::member_relationship($this->mid);
        $destroy = $redis->get('adc_destroy');
        if(empty($destroy)){
            $redis->set('adc_destroy',0);
            $destroy = 0;
        }
        $data = $redis->get('user_power_'.$this->mid);
        if(!empty($data)){
            $data = json_decode($data,true);
        }else{
            $data = [
                "total" => "0", //我的总算力 (节点算力)
                "pledge" => 0,  //我的质押算力
                "team" => 0,    //团队极差奖励
                "mining_volume" => "0", //我的开采量
                "surplus_mining_volume" => "0", //我剩余的开采量
                "recent_outputs" => "0",    //最近出产数量
                "mining_num" => 0,  //我的矿机总数量
                'recommend_arithmetical'    =>  0,
                'zhiya_recommend_arithmetical'  => 0,
                'team_nozhiya'  =>  0,
                'total_zhiya_recommend_arithmetical'    => 0,
            ];
        }

        $data['team_pledge'] = 0;   //团队质押  (质押投票算力)
        $data['team_total'] = 0;   //团队总算力(投票算力)
        $data['team_people'] = !empty($team['all']) ? count($team['all']) : 0;   //团队人数 (社区人数)
        $data['push_people'] = !empty($team[0]) ? count($team[0]) : 0;   //直推人数 (社区人数)
        $data['whole_network'] = $redis->get('totalArithmetical');   //全网总算力

        $adc_destroy = BaseConfigModel::config_data('adc_destroy');
        $adc_destroy = $adc_destroy ?: 0;
        $data['destroy']    =   bcadd($destroy,$adc_destroy,8);  //总算力销毁

        if(!empty($team['all'])){
            foreach ($team['all'] as $v){
                $team_data = $redis->get('user_power_'.$v['id']);
                if(!empty($team_data)){
                    $team_data = json_decode($team_data,true);
                    $data['team_total'] = bcadd($data['team_total'],$team_data['total'],8);
                    $data['team_pledge'] = bcadd($data['team_pledge'],$team_data['pledge'],8);
                }
            }
        }

        return api_success($data);
    }

    /**
     * 通过原始密码修改用户密码
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function up_password(){
        //原密码
        $password = $this->request->post('password', '', 'serach_in');
        if(empty($password)) return api_error('','Missing password',$this->language);
        //新密码
        $up_password = $this->request->post('up_password', '', 'serach_in');
        if(empty($up_password)) return api_error('','Missing password',$this->language);

        //原始密码不正确
        if(!MemberModel::verify_password($this->mid,$password)) return api_error('','The original password is incorrect',$this->language);

        //查询用户密码
        $member_password = MemberModel::password($this->mid)->toArray();
        //加密新密码
        $up_password = md5($up_password.$member_password['login_cryptosalt']);
        //修改密码
        MemberModel::up_password($this->mid,$up_password);

        return api_success();
    }

    /**
     * 根据密码查询私钥和助记词
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function mnemonic_or_key(){

        //查询用户密码
        $info = MemberModel::pass_mnemonic_key($this->mid)->toArray();

        $data = [
            'mnemonic'  =>  $info['mnemonic'],  //助记词
            'key'  =>  $info['private_key'] //私钥
        ];

        return api_success($data);
    }

    /**
     * 我的团队
     * @return \think\Response
     */
    function me_team(){
//        $member['zhitui'] = MemberModel::where('pid',$this->mid)->count();
//        $member['zhitui_ren'] = MemberModel::where('pid',$this->mid)->field('username,position,create_time')->select();
//        $member['team'] = MemberModel::where('team_id','like','%'.$this->mid.'%')->count();
//        $member = MemberModel::member_relationship_xiaohao($this->mid);
        return api_success(1);
    }

    /**
     * 所有等级
     */
    function level_list(){
        $member = MemberModel::getDetails($this->mid);
        $member_level = [
            'level_id'  =>  $member['level_id'],
            'level_name'    => '游客'
        ];
        $level = MemberLevelModel::getMemberList();
        $level_list = [];
        foreach ($level as $v){
            $level_list[] = [
                'id'    =>  $v['id'],
                'level' =>  $v['level'],
                'name'    =>  $v['name'],
                'e_name'    =>  $v['e_name'],
                't_name'    =>  $v['t_name'],
            ];
            if($v['id'] == $member['level_id']){
                $member_level['level_name'] = $v['name'];
                $member_level['level'] = $v['level'];
            }
        }
        api_success(['member'=>$member_level,'level_list'=>$level_list]);
    }

    function kp_info(){
        $wallet = MemberModel::wallet($this->mid)['waller'];
        //挖矿总产出
        $total_kangji = UserMoneyLog::where('mid',$this->mid)->where('cid',22)->where('type','Mining machine output')->sum('num');
        //查询总分红
        $total_fenhong = UserMoneyLog::where('mid',$this->mid)->where('cid',22)->where('type','IN',['Whole network dividend'])->sum('num');
        //团队分红
        $team_fenhong = UserMoneyLog::where('mid',$this->mid)->where('cid',22)->where('type','IN',['Community dividends','Direct deduction matrix reward'])->sum('num');
        //获取用户下一次升级
        $member = MemberModel::getDetails($this->mid);
        //获取当前用户等级详情
        $level = MemberLevelModel::getDetails($member['level_id']);
        $level_num = $level['level'] + 1;
        //获取下一级等级
        $upgrade_level = MemberLevelModel::getLevelDetails($level_num);

        //获取用户信息
        $member = MemberModel::getDetails($this->mid);
        $level = MemberLevelModel::getDetails($member['level_id']);
        $level_name = '';
        switch ($this->language){
            case 'english': $level_name = $level['e_name']; break;
            case 'traditional': $level_name = $level['t_name']; break;
            case 'simplified': $level_name =  $level['s_name']; break;
        }

        $data = [
            'liudongsuanli' =>  $wallet[23]['money'], //LP算力
            'total_kuangji'      =>  $total_kangji,
            'toal_fenhong'  =>  $total_fenhong,
            'team_fenhong'  =>  $team_fenhong,
            'level_name'    =>  $level_name,
            'dengjisuanli'  =>  $member['power'],  //KR冻结    挖矿可领取
            'dengjifenhong' =>  $wallet[1]['money'],
            'dengjifenhong_kr'  =>  bcadd($wallet[22]['money'],$wallet[22]['freeze_money'],8),   //KR余额 可领取数量团队分红
            'dengjifenhong_usdt'  =>  $wallet[1]['money'],   //usdt余额 团队分红
            'up_level_usdt' =>  !empty($upgrade_level) ? $upgrade_level['pay_amount'] : -1,  //升级所需要的USDT
        ];

        api_success($data);
    }

    function authorized_dividends(){
        common::authorized_dividends();
    }

    function usdtvkr(){
        $member = MemberModel::getDetails($this->mid);
        $headers = [
            'headers' => [
                'accept'=>'application/json',
                'content-type'=>'application/json',
                'sign'  =>  md5(env('HEADER_SIGN').'address:'.$member['username'])
            ]
        ];
        $client = new \GuzzleHttp\Client($headers);
        $options = ['form_params'   =>  ['address'=>$member['username']]];
        $response = $client->request('POST', env('HEYUEURL_EMPOWER').'getUSDTLimit', $options);
        $response_data = json_decode($response->getBody(),true);
        if(is_array($response_data)){
            if($response_data['code'] == 1){
                api_success($response_data['data']);
            }else{
                api_error('','empty',$this->language);
            }
        }
        api_error('','empty',$this->language);
    }
}